package apis

import (
	"gitee.com/sansaniot/ssiot-core/httpmvc/api"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	cDto "ssdevice/common/dto"
	"ssdevice/internal/device/models"
	"ssdevice/internal/device/models/command"
	"ssdevice/internal/device/models/query"
	"strings"
)

type ReportForms struct {
	api.Api
}

// 查询报表表单列表
func (e ReportForms) FindReportFormList(c *gin.Context) {
	// 请求参数
	req := query.SysReportFormsQuery{}
	// 模型
	m := models.SysReportForms{}
	// 上下文
	err := e.MakeContext(c).Bind(&req).MakeModel(&m.Model).Errors
	if err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}
	// 执行
	var result interface{}
	req.LoadUser(c)
	if err, result = m.FindReportFormsList(&req); err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}
	// 返回
	e.Ok(result)
}

// 添加报表表单
func (e ReportForms) AddReportForms(c *gin.Context) {
	// 请求参数
	req := command.ReportFromInsertReq{}

	// 上下文
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}
	// 用户信息
	req.LoadUser(c)
	// 执行
	var reportForms models.SysReportForms
	if err = req.Generate(&reportForms); err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}
	req.UserId = req.UserInfo.UserName
	reportFormsModel := &models.SysReportForms{}
	reportFormsModel.Orm = e.Orm
	if err = reportFormsModel.Add(reportForms); err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}
	// 返回
	e.Data(reportForms)
}

// 删除报表表单
func (e ReportForms) DeleteReportForms(c *gin.Context) {
	// 请求参数
	req := command.ReportFromDeleteReq{}

	// 上下文
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}
	// 用户信息
	req.LoadUser(c)
	// 执行
	reportFormsModel := &models.SysReportForms{}
	reportFormsModel.Orm = e.Orm
	delIds := strings.Split(strings.ReplaceAll(req.Id, " ", ""), ",")
	if err = reportFormsModel.Delete(&models.SysReportForms{}, cDto.MakeCondition(query.SysReportFormsQuery{IdIn: delIds})); err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}
	// 返回
	e.Ok(nil)
}
